<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>会员列表</h3>
    </div>
    <el-form :model="searchForm" ref="searchFormRef" label-width="82px" style="padding-bottom: 1.5rem">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="用户信息：" prop="queryName">
            <el-input placeholder="请输入用户名" v-model="searchForm.queryName" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号：" prop="queryMobile">
            <el-input placeholder="请输入手机号" v-model="searchForm.queryMobile" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="会员级别：" prop="clubCardId">
            <el-select v-model="searchForm.clubCardId" placeholder="请选择会员级别" clearable @change="getData">
              <el-option v-for="item in vipList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="到期状态：" prop="vipExpireState">
            <el-select v-model="searchForm.vipExpireState" placeholder="请选择到期状态" clearable @change="getData">
              <el-option v-for="item in statusOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <form-input label="用户信息" prop="queryName" v-model="searchForm.queryName" /> -->
        <!-- <form-input label="手机号" prop="queryMobile" v-model="searchForm.queryMobile" /> -->
        <!-- <form-select label="会员级别" prop="clubCardId" v-model="searchForm.clubCardId" :options="vipList" /> -->
        <!-- <form-select label="到期状态" prop="vipExpireState" v-model="searchForm.vipExpireState" :options="statusOption" /> -->
      </el-row>
      <el-row :gutter="24">
        <el-col :span="6">
          <div class="databox">
            <label class="el-form-item__label" style="margin-left: 1.5rem">开通时间：</label>
            <el-date-picker label="开通时间：" v-model="datavalue1" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="openTime" />
          </div>
        </el-col>
      </el-row>
    </el-form>

    <art-table :data="tableData" selection :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
      :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <!-- @click="linkuserdetails()" -->
        <el-table-column label="用户信息" prop="avatar" #default="scope" width="300px" v-if="columns[0].show"
          style="cursor: pointer">
          <div class="user" style="display: flex; align-items: center; cursor: pointer">
            <img class="avatar" :src="scope.row.avatar" v-if="scope.row.avatar" />
            <div>
              <el-dropdown placement="top-end">
                <el-link underline="never">{{ scope.row.realName }}</el-link>
                <!-- <div>{{ scope.row.realName }}</div> -->
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <p>{{ scope.row.realName }} ID:{{ scope.row.memberId }}</p>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <p class="email">ID:{{ scope.row.memberId }}</p>
            </div>
          </div>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" align="center" />
        <el-table-column label="会员权益" prop="clubCardName" align="center">
          <template #default="scope">
            <!-- <div class="checkMore" v-if="scope.row.vipCountState == 1" @click="openVipDialogVisible(scope.row)">
              查看更多
            </div> -->
            <div v-if="scope.row.vipCountState == 1">
              {{ scope.row.clubCardNames }}
            </div>
            <div v-else>{{ scope.row.clubCardName }}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="订单来源" prop="sources" align="center" />
        <el-table-column label="订单渠道" prop="vipOpenType" align="center">
          <template #default="scope">
            <div v-if="scope.row.vipCountState == 1">
              {{ scope.row.vipOpenTypes }}
            </div>
            <div v-else>{{ scope.row.vipOpenType === 1 ? '线上购买' : scope.row.vipOpenType === 2 ? '兑换码兑换' : '新人礼包' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="开通时间" prop="vipStartTime" sortable align="center" /> -->
        <el-table-column label="到期状态" prop="vipExpireState" align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.vipExpireState)">
              {{ buildTagText(scope.row.vipExpireState) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="到期时间" prop="vipEndTime" sortable align="center" />
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="editPassword" @click="openVipDialogVisible(scope.row)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加用户' : '编辑用户'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户信息" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="用户id" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="formData.sex">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源" prop="dep">
          <el-select v-model="formData.dep">
            <el-option label="微信小程序" :value="1" />
            <el-option label="IOS" :value="2" />
            <el-option label="安卓" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="vipDialogVisible" title="会员卡信息" width="50%" :close-on-click-modal="false">
      <art-table :data="openVipData" :loading="tableLoading" :currentPage="openVipPageNum" :pageSize="openVipPageSize"
        :total="openVipPageTotal" @current-change="openVipCurrentChange" @size-change="openVipSizeChange">
        <template #default>
          <el-table-column label="会员权益" prop="clubCardName" align="center" />
          <el-table-column label="订单来源" prop="source" align="center">
            <template #default="score">
              {{
                score.row.source === 0
                  ? '兑换码兑换'
                  : score.row.source === 1
                    ? '新人礼包发放'
                    : score.row.source === 2
                      ? '老带新'
                      : score.row.source === 3
                        ? '线上购买'
                        : ''
              }}
            </template>
          </el-table-column>
          <el-table-column label="订单渠道" prop="orderChannel" align="center">
            <template #default="score">
              {{
                score.row.orderChannel === 0
                  ? 'APP'
                  : score.row.orderChannel === 1
                    ? '微信公众号'
                    : score.row.orderChannel === 2
                      ? '微信小程序'
                      : score.row.orderChannel === 3
                        ? '学员pc端'
                        : ''
              }}
            </template>
          </el-table-column>
          <el-table-column label="开通日期" prop="shoppingTime" sortable v-if="columns[5].show" align="center" />
          <el-table-column label="订单号" prop="ordersNo" align="center" />
          <el-table-column label="到期状态" prop="status" :filters="[
            { text: '已到期', value: '1' },
            { text: '未到期', value: '0' }
          ]" :filter-method="filterTag" filter-placement="bottom-end" v-if="columns[4].show" align="center">
            <template #default="scope">
              <el-tag :type="getTagType(scope.row.status)">
                {{ buildTagText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="到期时间" prop="vipEndTime" sortable v-if="columns[5].show" align="center" />
        </template>
      </art-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ACCOUNT_TABLE_DATA } from '@/mock/temp/huiyuanlist'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { vipListData, vipType, userOpenVip } from '@/api/userStudentsApi'

const dialogType = ref('add')
const dialogVisible = ref(false)
const vipDialogVisible = ref(false)
const datavalue1 = ref('') //创建时间：
const router = useRouter() // 使用useRouter获取路由实例

const formData = reactive({
  username: '',
  phone: '',
  sex: '',
  dep: '',
  userleavel: ''
})

const statusOption = [
  {
    value: '1',
    label: '已到期'
  },
  {
    value: '0',
    label: '未到期'
  }
]
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])

const searchFormRef = ref<FormInstance>()
interface search {
  queryName: string,
  queryMobile: string
  vipTimeQueryStartTime: string
  vipTimeQueryEndTime: string
  endTime: string
  clubCardId: string
  vipExpireState: string
}
const searchForm = reactive<search>({
  queryName: '',
  queryMobile: '',
  vipTimeQueryStartTime: '',
  vipTimeQueryEndTime: '',
  endTime: '',
  clubCardId: '',
  vipExpireState: ''
})
const openTime = (e: any) => {
  if (e) {
    searchForm.vipTimeQueryStartTime = e[0]
    searchForm.vipTimeQueryEndTime = e[1]
  } else {
    searchForm.vipTimeQueryStartTime = ''
    searchForm.vipTimeQueryEndTime = ''
  }
  getData()
}
const resetForm = (formEl: FormInstance | undefined) => {
  console.log(formEl);

  if (!formEl) return
  formEl.resetFields()
  searchForm.vipTimeQueryEndTime = ''
  searchForm.vipTimeQueryStartTime = ''
}

const tableData = ref([])
//编辑用户
// const showDialog = (type: string, row?: any) => {
//   dialogVisible.value = true
//   dialogType.value = type

//   if (type === 'edit' && row) {
//     formData.username = row.username
//     formData.phone = row.mobile
//     formData.sex = row.sex === 1 ? '男' : '女'
//     formData.dep = row.dep
//   } else {
//     formData.username = ''
//     formData.phone = ''
//     formData.sex = '男'
//     formData.dep = ''
//   }
// }
const linkuserdetails = function () {
  setTimeout(() => {
    router.push('/user_student/UserDetails')
  }, 300)
}

const vipList = ref<any>([])
const getVipData = async () => {
  const res = await vipType()
  vipList.value = res.data
}
const deleteUser = () => {
  ElMessageBox.confirm('确定要注销该用户吗？', '注销用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    ElMessage.success('注销成功')
  })
}

const search = () => {
  getData()
}

const changeColumn = (list: any) => {
  columns.values = list
}

const filterTag = (value: string, row: any) => {
  return row.status === value
}

const getTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'danger'
    default:
      return 'primary'
  }
}

const buildTagText = (status: number) => {
  let text = ''
  if (status === 1) {
    text = '已到期'
  } else {
    text = '未到期'
  }
  return text
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  dep: [{ required: true, message: '请选择来源', trigger: 'change' }]
})

const formRef = ref<FormInstance>()

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
    }
  })
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true
    searchForm.vipTimeQueryStartTime = searchForm.vipTimeQueryStartTime ? formatDate(searchForm.vipTimeQueryStartTime) : ''
    searchForm.vipTimeQueryEndTime = searchForm.vipTimeQueryStartTime ? formatDate(searchForm.vipTimeQueryEndTime) : ''
    const params = filterEmptyValues(searchForm)
    console.log(params);
    const { code, data } = await vipListData({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...params
    })
    if (code === '00000' && data) {
      tableData.value = data
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== undefined && obj[key] !== null) {
      result[key] = obj[key]
    }
  }
  return result
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const openVipDialogVisible = (row: any) => {
  vipDialogVisible.value = true
  getOpenVipData(row)
}

const openVipData = ref([])
const openVipPageNum = ref(1)
const openVipPageSize = ref(10)
const openVipPageTotal = ref(0)
async function getOpenVipData(row: any) {
  try {
    tableLoading.value = true
    const { code, data } = await userOpenVip({
      pageNum: openVipPageNum.value,
      pageSize: openVipPageSize.value,
      memberId: row.memberId
    })
    if (code === '00000' && data) {
      openVipData.value = data
      openVipPageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const openVipCurrentChange = (val: number) => {
  openVipPageNum.value = val
}


const openVipSizeChange = (val: number) => {
  openVipPageSize.value = val
  openVipPageNum.value = 1
}
onMounted(() => {
  getData()
  getVipData()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}

.table-bar {
  padding: 0;
}

.checkMore {
  font-size: 12px;
  color: #67c23a;
  cursor: pointer;
}
</style>
